package com.gl.order.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gl.order.commom.ResultBean;
import com.gl.order.commom.excetion.ServiceExcetion;
import com.gl.order.entity.SystemDict;
import com.gl.order.entity.TUser;
import com.gl.order.entity.TUserRole;
import com.gl.order.entity.dto.EditPwdDto;
import com.gl.order.entity.dto.UpdateUserDto;
import com.gl.order.entity.dto.UserAddDto;
import com.gl.order.entity.dto.UserPageDto;
import com.gl.order.entity.vo.UserAndRoleCodeVo;
import com.gl.order.entity.vo.UserPageVo;
import com.gl.order.mapper.TUserMapper;
import com.gl.order.mapper.TUserRoleMapper;
import com.gl.order.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author lsy
 * @Date 2021/5/18 15:42
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<TUserMapper,TUser> implements UserService {


    @Autowired
    TUserRoleMapper userRoleMapper;

    @Override
    public TUser findUserByAccount(String account) {
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TUser::getAccount,account);
        TUser user =  getOne(queryWrapper);
        Optional<TUser> empty = Optional.ofNullable(user);
        return empty.orElse(null);
    }

    @Override
    public Map<String, UserAndRoleCodeVo> findByRoleCode(List<String> roleCodes) {
        if (null == roleCodes || roleCodes.size() <= 0) {
            return new HashMap();
        }
        List<UserAndRoleCodeVo> users = baseMapper.findByRoleCode(roleCodes);
        Map map = users.stream().collect(Collectors.groupingBy(UserAndRoleCodeVo::getRoleCode, HashMap::new, Collectors.toList()));
        return map;
    }

    @Override
    public TUser findById(String id) {
        return getById(id);
    }


    @Override
    public void add(UserAddDto dto) {
        TUser user = new TUser();
        BeanUtils.copyProperties(dto,user);
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        save(user);
        if(CollUtil.isNotEmpty(dto.getRoleIds())){
            addUserRole(user.getId(),dto.getRoleIds());
        }
    }

    @Override
    public void update(UpdateUserDto dto) {
        TUser check =  findById(dto.getId());
        if(Objects.isNull(check)){
            throw  new NullPointerException("请确认需要修改的用户");
        }
        TUser user = new TUser();
        BeanUtils.copyProperties(dto,user);
        updateById(user);
        if(CollUtil.isNotEmpty(dto.getRoleIds())){
            addUserRole(dto.getId(),dto.getRoleIds());
        }
    }

    @Override
    public void addUserRole(String id, List<String> roleIds) {
        // 添加新角色前先删除之前存在的角色
        delRoleByUser(id);
        roleIds.stream().forEach(roleId -> {
            userRoleMapper.insert(new TUserRole(id,roleId));
        });
    }

    @Override
    public void delRoleByUser(String userId) {
        QueryWrapper<TUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TUserRole::getUserId,userId);
        userRoleMapper.delete(queryWrapper);
    }

    @Override
    public void delUser(String userId) {
        delRoleByUser(userId);
        removeById(userId);
    }

    @Override
    public void delByids(List<String> ids) {
        if(!CollectionUtils.isEmpty(ids)){
            ids.stream().forEach(userId -> {
                delUser(userId);
            });
        }
    }

    @Override
    public List<TUser> list() {
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        return list(queryWrapper);
    }

    @Override
    public IPage<UserPageVo> pageOfUser(UserPageDto dto) {
        Page<UserPageVo> page = new Page(dto.getPageNo(),dto.getPageSize());
        IPage<UserPageVo> userPageVos = baseMapper.pageOfUser(page, dto);
        userPageVos.getRecords().stream().forEach(userPageVo -> {
            userPageVo.setRoleIds(baseMapper.getRoles(userPageVo.getId()));
        });
        return userPageVos;
    }

    @Override
    public void editPassword(EditPwdDto dto) {
        TUser user = getById(dto.getId());
        Assert.notNull(user,"用户不存在");
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if(!bCryptPasswordEncoder.matches(dto.getPwd(),user.getPassword())){
            throw new ServiceExcetion(ResultBean.FAIL,"原密码不正确");
        }
        String npwd = bCryptPasswordEncoder.encode(dto.getNpwd());
        user.setPassword(npwd);
        updateById(user);
    }

//    public static void main(String[] args) {
//       String pwd =  new BCryptPasswordEncoder().encode("123456");
//        System.out.println(pwd);
//    }

}
